<template>
    <!-- <div v-bind:class="[isExpand ? 'expand' : '', 'leftSideListCan']" ref="leftSideListCan"> -->
    <div class="leftSideListCan" ref="leftSideListCan">
        <div class="listContainer">
            <!-- <p class="toggleBtn">
                <img @click="toggleLeftMenu" src="@/assets/img/form_next.png" alt="">
            </p>-->
            <div>
                <el-tree 
                    ref="tree"
                    :data="list" 
                    :props="defaultProps" 
                    node-key="name" 
                    @node-click="handleNodeClick"
                    :default-expanded-keys="keys"
                    :highlight-current="true"
                    :indent="40"
                >
                </el-tree>
            </div>
        </div>
    </div>
</template>
<script>
    import route from '@/router';
    import { mapGetters } from 'vuex';
    import { DRcookie } from '@/assets/js/common.js'
    export default {
        data() {
            return {
                keys: [],
                list: [],
                defaultProps: {
					children: 'children',
					label: 'label'
				},
                showList: true,
                backUp: {},
				isExpand:false
            }
        },
        computed: {
            // 打开的页面
            ...mapGetters('qxz', [
                "getOpeningPages"
            ])
        },
        mounted() {
            this.$emit('setWidth')
            PSEvent.listen('adjust_menu', () => {
                this.toggleItem(this.backUp)
            })
            // let screenWidth = document.documentElement.clientWidth;
            // if(screenWidth < 800) {
            //     this.$refs.leftSideListCan.classList.add('positionContainer')
            // }else {
            //     this.$refs.leftSideListCan.classList.remove('positionContainer')
            // }
        }, 
        methods: {
            // 当前的路由的子模块
            getModule() {
                let temp, path = this.$route.path;
                let moduleName = path.split('/')[1]
                moduleName && route.options.routes.map(ele => {
                    if(moduleName === ele.name) {
                        temp = ele
                    }
                })
                return temp
            },
            // 切换tab生成列表
            generateList() {
                let redirection = ''
                this.list = []
                // 展开项，左侧图标，选中的子项
                let keyArr = [];
                let uriList = [];
                let childKey;
                let modules = this.getModule()
                let listConfig = localStorage.getItem('menuInfoList') ? JSON.parse(localStorage.getItem('menuInfoList')) : '';
                if(!Array.isArray(listConfig) || listConfig.length === 0) {
                    this.$router.replace({name: 'login'})
                    return
                }
                // 权限列表的当前模块
                let matchedModule = listConfig.filter(ele => {
                    return (ele.menu_url === modules.name && ele.parent_id === 200)
                });
                // 2级菜单
                let secArr = []
                listConfig.forEach(ele => {
                    if(ele.parent_id === matchedModule[0].id) {
                        secArr.push(ele)
                    }
                })
                // 3级菜单
                let thirdArr = []
                listConfig.forEach(ele => {
                    secArr.forEach(item => {
                        if(item.id === ele.parent_id) {
                            ele.parent_name = item.menu_name
                            thirdArr.push(ele)
                        }
                    })
                })
                if(modules && modules.children) {
                    modules.children.map((ele, index) => {
                        if(!ele.redirect) {
                            thirdArr.forEach(item => {
                                if(item.menu_name === ele.label && item.parent_name === ele.className) {
                                    let flag = true;
                                    // 默认的跳转路径
                                    ele.historyPath = `/${ele.module}/${ele.path}`
                                    // 这个是当前路由
                                    let matchedRoute = ele.name === this.$route.name
                                    // 向目录列表中添加项目
                                    this.list.forEach(item => {
                                        // 有这个父类。添加子项
                                        if(item.label === ele.className) {
                                            // 子页面的跳转页面,不添加到列表中
                                            if(ele.unlist) {
                                                // 当前路由对应的就是这个子页面
                                                if(matchedRoute) {
                                                    // 路由匹配选中跳转源页面
                                                    childKey = ele.generatedBy
                                                    // 修正跳转路径
                                                    item.children.map(kits => {
                                                        kits.name === childKey && (kits.historyPath = `/${ele.module}/${ele.path}`)
                                                    })
                                                }
                                            }else {
                                                // 添加子项
                                                matchedRoute && (childKey = ele.name)
                                                item.children.push(ele);
                                            }
                                            // 需要展开的一级列表
                                            matchedRoute && keyArr.push(item.name)
                                            // 是否有这个大类的flag,这里添加了不再执行下面的添加大类操作
                                            flag = false
                                        }
                                    })
                                    if(flag) {
                                        this.list.push({
                                            name: index,
                                            label: ele.className,
                                            children: [ele]
                                        })
                                        // 添加左侧图标数组
                                        ele.iconUri ? uriList.push(ele.iconUri) : uriList.push(require('@/assets/img/nav_box_normal.png'))
                                        // 展开当前页面组
                                        matchedRoute && keyArr.push(index)
                                        // 如果路由匹配选中子项
                                        matchedRoute && (childKey = ele.name)
                                        if(redirection === '') {
                                            redirection = ele.name
                                        }
                                    }
                                }
                            })
                        }
                    })
                    // 重定向
                    if(redirection && this.$route.matched.length === 1) {
                        this.$router.replace({name: redirection})
                    }
                }
                // 展开选中子项的集合,选中子项
                this.$nextTick(() => {
                    // 修正左侧图标
                    let tree = document.querySelector('.el-tree')
                    let node = tree.firstChild
                    let nodeArr = []
                    this.$refs.tree.$children.map((ele, index) => {
                        let el = ele.$el
                        let titleCan = el.querySelector('.el-tree-node__content')
                        let target = titleCan.querySelector('.el-tree-node__expand-icon')
                        target.style.background = `url(${uriList[index]}) center center/20px 20px no-repeat`
                    })
                    
                    this.keys = keyArr
                    this.$refs.tree && this.$refs.tree.setCurrentKey(childKey || this.$route.name);
                })
            },
            // 未切换tab点击列表
            toggleItem(newVal) {
                let currentRoute = this.mathchUnlistRoute();
                // 展开对应列表
                this.list && this.list.map(item => {
                    item.children.map(ele => {
                        if(ele.name === this.$route.name || ele.name === currentRoute.generatedBy) {
                            // 直接跳转子页面
                            if(currentRoute.generatedBy) {
                                this.$refs.tree.setCurrentKey(currentRoute.generatedBy)
                                // 加上参数
                                let query = this.$route.query;
                                let str = ''
                                for(let key in query) {
                                    str += `${key}=${query[key]}&`
                                }
                                str && (str = str.substr(0, str.length - 1))
                                ele.historyPath = `/${currentRoute.module}/${currentRoute.path}${str ? '?' : ''}${str}`
                            }else {
                                this.$refs.tree.setCurrentKey(newVal.name)
                                ele.historyPath = `/${ele.module}/${ele.path}`
                            }
                            this.keys = [item.name]
                        }
                    })
                })
            },
            // 匹配子页面
            mathchUnlistRoute() {
                // 当前路由
                let currentRoute = {}
                this.getModule().children.map(ele => {
                    if(ele.unlist && ele.name === this.$route.name) {
                        currentRoute = ele
                    }
                })
                return currentRoute
            },
            toggleLeftMenu() {
				this.isExpand = !this.isExpand;
			},
            // 点击子项
            handleNodeClick(item) {
                let isOpened = false;
                Array.isArray(this.getOpeningPages) && this.getOpeningPages.map(ele => {
                    (item.name === ele.name || item.name === ele.generatedBy) && (isOpened = ele)
                })
                // 没有打开或已经关闭的页面跳转初始默认页面, 已经打开的跳转记录的页面
                item.path && (isOpened ? this.$router.push({path: isOpened.historyPath}) : this.$router.push({path: `/${item.module}/${item.path}`}))
            },
            // 权限鉴别
            getLimitedList(newVal) {
                // 是否允许访问
                let accessDenied = false
                let modules = this.getModule()
                let listConfig = localStorage.getItem('menuInfoList') ? JSON.parse(localStorage.getItem('menuInfoList')) : '';
                if(!Array.isArray(listConfig) || listConfig.length === 0) {
                    this.$message({
                        message: '无访问权限',
                        type: 'warning'
                    })
                    this.$router.replace({name: 'login'})
                    return
                }
                // 权限列表的当前模块
                let matchedModule = listConfig.filter(ele => {
                    return (ele.menu_url === modules.name && ele.parent_id === 200)
                });
                // 2级菜单
                let secArr = []
                listConfig.forEach(ele => {
                    if(ele.parent_id === matchedModule[0].id) {
                        secArr.push(ele)
                    }
                })
                // 3级菜单
                let thirdArr = []
                listConfig.forEach(ele => {
                    secArr.forEach(item => {
                        if(item.id === ele.parent_id) {
                            ele.parent_name = item.menu_name
                            thirdArr.push(ele)
                        }
                    })
                })
                // 当前3级菜单
                let thirdConfig = ''
                if(modules && modules.children) {
                    modules.children.map((ele, index) => {
                        if(!ele.redirect) {
                            // 没有权限的页面，提示后跳回去
                            thirdArr.forEach(item => {
                                if(item.menu_name === ele.label && item.parent_name === ele.className) {
                                    if(ele.name === newVal.name) {
                                        thirdConfig = item
                                    }
                                }
                            })
                        }
                    })
                }
                if(thirdConfig) {
                    if(thirdConfig.menu_url === this.$route.name) {
                        accessDenied = true
                    }
                    listConfig.forEach(ele => {
                        if(ele.parent_id === thirdConfig.id) {
                            if(ele.menu_url === this.$route.name) {
                                accessDenied = true
                            }
                        }
                    })
                    if(!accessDenied) {
                        this.$message({
                            message: '无访问权限',
                            type: 'warning'
                        })
                        setTimeout(() => {
                            this.$router.go(-1)
                        }, 0)
                    }
                }

            }
        },
        watch: {
            $route: {
                immediate: true,
                handler: function (newVal, oldVal) {
                    // 缓存路由信息
                    this.backUp = newVal;
                    // 刷新、第一次开页面、切换顶部tab,重新生成对应list : 切换二级页面
                    if(!oldVal) {
                        this.generateList()
                    }else if(oldVal.path.split('/')[1] !== newVal.path.split('/')[1]) {
                        this.generateList()
                    }else {
                        this.toggleItem(newVal)
                    }
                    setTimeout(() => {
                        this.getLimitedList(newVal);
                    }, 0)
                }
            }
        }
    }
</script>
<style scoped lang="less">
	
    .leftSideListCan{
        width: 210px;
        height: 100%;
        background: #e9e9e9;
        /* position: absolute;
        z-index: 99999; */
    }
    .listContainer{
        width: 210px;
        height: 100%;
    }
	/* 展开的样式 */
	.expand{
		width: 210px !important;
	}
	.expand .listContainer{
		width: 210px !important;
	}
	.expand{
		/deep/ .listContainer{
			.el-tree-node__label{
				display: block !important;
			}
		}
		
	}
	.expand{
		/deep/ .listContainer{
			.el-tree-node__children{
				display: block !important;
			}
		}
		
	}
	
    .positionContainer {
        position: absolute;
    }
	.toggleBtn{
		display: none;
	}
	@media screen and (max-width: 1200px) {
		.toggleBtn{
			height: 32px;
			box-shadow: inset 0px -1px 0px 0px #cccccc;
			display: flex;
			align-items: center;
			justify-content:flex-end;
		}
		.toggleBtn img{
			margin: 0 20px;
			cursor: pointer;
		}
		/*.leftSideListCan{
		    width: 52px;
		    height: 100%;
		    background: #e9e9e9;
		    /* position: absolute;
		    z-index: 99999; 
		}
		.listContainer{
		    width: 52px;
		    height: 100%;
		}
		/deep/ .listContainer{
			.el-tree-node__label{
				display: none !important;
			}
		}
		/deep/ .listContainer{
			.el-tree-node__children{
				display: none !important;
			}
		}*/
		
	}
</style>